const message = require('../model/returnMessage');
const md5 = require('../utils/md5');
const { server } = require('../config/config.default');
const { postID } = require('../utils/postid');
const fs = require('fs');
const path = require('path');
const {
  getNearestPost,
  getNearestPostByAuthor,
  getPostInfoById,
  setPostText,
  deletePostById,
  addPost,
} = require('../model/post');

module.exports.getNearestPost = async (req, res, next) => {
  const { current_page, page_size } = req.body;
  getNearestPost({ current_page, page_size }).then(
    (r) => {
      res.status(200).json(message(r, 'Posts returned.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.getNearestPostByAuthor = async (req, res, next) => {
  const { authors, current_page, page_size } = req.body;
  if (authors.length <= 0) {
    res.status(401).json(message({}, 'There must be more than one person.'));
  }
  getNearestPostByAuthor({ authors, current_page, page_size }).then(
    (r) => {
      res.status(200).json(message(r, 'Posts returned.'));
    },
    (e) => {
      res.status(500).json(message({}, e));
    }
  );
};

module.exports.getPostInfoById = async (req, res, next) => {
  getPostInfoById(req.body.id).then(
    (r) => {
      res.status(200).json(message(r[0], 'Posts returned.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.setPostText = async (req, res, next) => {
  const { id, text } = req.body;
  setPostText({ post_id: id, post_text: text }).then(
    (r) => {
      res.status(200).json(message(r, 'Posts edited.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.deletePostById = async (req, res, next) => {
  deletePostById(req.body.id).then(
    (r) => {
      res.status(200).json(message(r, 'Posts deleted.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.addPost = async (req, res, next) => {
  const { author, text, id } = req.body;
  addPost({ post_author: author, post_text: text, post_id: id }).then(
    (r) => {
      res.status(200).json(message({ author, id }, 'Post created.'));
    },
    (e) => {
      res.status(500).json(message({}, 'Internal server error'));
    }
  );
};

module.exports.getId = async (req, res, next) => {
  let _id = postID();
  fs.mkdir(path.join('./public/post', _id), function (err) {
    if (err) {
      res.status(500).json(message({}, 'Internal server error.'));
    } else {
      res.status(200).json(message({ id: _id }, 'Id created.'));
    }
  });
};
